<template>
  <div class="tab-content single-ingot">
    <el-scrollbar>
      <div class="top-card-container">
        <dataCard :dataArr="cardList" :code="statusCode"></dataCard>
      </div>
    </el-scrollbar>
    <BasicCard style="margin-bottom: 20px">
      <BasicVxeTable ref="gridRef" v-bind="gridOptions" v-on="gridEvents"></BasicVxeTable>
      <div class="singleIngot-detail" v-show="showDetail">
        <BasicVxeTable ref="gridRefIngot" v-bind="gridOptionsIngot">
          <template #state="{ row }">
            <el-tag effect="dark" type="warning" v-if="row.state === 0">正常</el-tag>
            <el-tag effect="dark" type="danger" v-if="row.state === 1">断头</el-tag>
            <el-tag effect="dark" type="warning" v-if="row.state === 2">弱捻</el-tag>
            <el-tag effect="dark" type="primary" v-if="row.state === 3">不良</el-tag>
            <el-tag effect="dark" color="#FFA2D3" v-if="row.state === 4">空锭</el-tag>
          </template>
        </BasicVxeTable>
      </div>
    </BasicCard>
    <BasicCard>
      <BasicVxeTable ref="gridRefBroken" v-bind="gridOptionsBroken"></BasicVxeTable>
    </BasicCard>
  </div>
</template>

<script setup lang="ts">
  import dataCard from '../../../businessComponents/dataCard.vue'
  import { dataRegroup } from '../../utils'
  import {
    overallUnitTableColumns,
    singleIngotTableColumns,
    brokenEndTableColumns
  } from '../../data'
  import { overallUnitType, singleIngotType, brokenEndType } from '../../types'
  import type { VxeGridListeners } from 'vxe-table'
  import dayjs from 'dayjs'
  import { getJiTaiZhuangTai, getRuoNianList, getLiShiZhuangTai } from '@/api/shengChanJianShi'
  import { getJiTaiAndWuLiao } from '@/api/gongGongChaXun'

  defineProps({
    statusCode: {
      // 工序id
      type: String,
      default: ''
    }
  })

  const { t } = useI18n()
  const clearTimeSet = ref()
  const canRefresh = ref(true)
  const gridRef = ref<BasicGridInstance>()
  const gridRefBroken = ref<BasicGridInstance>()
  // 机台选择项的弹框中数据
  const filterProcessList = ref([])
  // 单锭详情显示隐藏
  const showDetail = ref(false)

  const gridOptions = reactive<BasicGridProps>({
    extraConfig: {
      title: t('custom.整机状态'),
      isCustom: true,
      isExport: true,
      isFilterAndSort: true
    }, // 拓展的配置
    id: `realtime-single-ingot-status`, // id用于缓存,务必配置
    toolbarConfig: {}, // 工具栏
    maxHeight: 500,
    exportConfig: {
      filename: '数据表'
    },
    proxyConfig: {
      autoLoad: false,
      showLoading: false, // 关闭加载中
      ajax: {
        query: () => {
          // 默认接收 Promise<any[]>
          return getCardAndOverallUnitData()
        }
      }
    },
    // data: [],
    columns: overallUnitTableColumns
  })
  const gridOptionsIngot = reactive<BasicGridProps>({
    extraConfig: {
      title: t('custom.单锭详情'),
      isCustom: false,
      isExport: false,
      isFilterAndSort: false
    }, // 拓展的配置
    id: `realtime-single-ingot-detail`, // id用于缓存,务必配置
    toolbarConfig: {}, // 工具栏
    exportConfig: {
      filename: '数据表'
    },
    maxHeight: 200,
    proxyConfig: {
      autoLoad: false,
      // showLoading: false, // 关闭加载中
      ajax: {
        query: () => {
          // 默认接收 Promise<any[]>
          return getSingleIngotData()
        }
      }
    },
    columns: singleIngotTableColumns
  })

  const gridOptionsBroken = reactive<BasicGridProps>({
    extraConfig: {
      title: t('custom.断头(弱捻)情况'),
      isCustom: true,
      isExport: true,
      isFilterAndSort: true
    }, // 拓展的配置
    id: `realtime-single-ingot-broken`, // id用于缓存,务必配置
    toolbarConfig: {}, // 工具栏
    exportConfig: {
      filename: '数据表'
    },
    maxHeight: 500,
    proxyConfig: {
      autoLoad: false,
      showLoading: false, // 关闭加载中
      ajax: {
        query: () => {
          // 默认接收 Promise<any[]>
          return getBrokenEndList()
        }
      }
    },
    columns: brokenEndTableColumns
  })

  // 获取物料和机台列表
  const machineryIdArr = ref<any>([])
  const machineryNameArr = ref<any>([])
  const getMaterialsAndMachineryData = () => {
    getJiTaiAndWuLiao().then((res: any) => {
      const backupJson: any = [...res]
      for (const item of backupJson) {
        item.check = true
        item.text = item.text === '' || item.text == null ? '(未设置品种)' : item.text
        for (let value of item.childNodes) {
          value.check = true
        }
      }

      // 用于表单筛选中的机台选择项的弹框中数据
      filterProcessList.value = backupJson

      if (backupJson.length > 0) {
        for (let item of backupJson) {
          const childNodes = item.childNodes || []
          const selected = childNodes.filter((node) => node.check)

          if (selected.length > 0) {
            machineryIdArr.value.push(...selected.map((node) => node.id))
            machineryNameArr.value.push(...selected.map((node) => node.text))
          }
        }
      }
      // 调取grid的query方法
      gridRef.value?.$grid?.commitProxy('query')
      gridRefBroken.value?.$grid?.commitProxy('query')
      // getCardAndOverallUnitData('once')
      // getBrokenEndList()
    })
  }

  // 获取整机状态表格数据和顶部卡片数据
  const cardList = ref<any[]>([])
  const getCardAndOverallUnitData = () => {
    return new Promise<overallUnitType[]>((resolve) => {
      getJiTaiZhuangTai(machineryIdArr.value).then((res: any) => {
        const machineValue = res.machineStateSummary
        const tempValue = { ...machineValue }
        tempValue.brokenEndBoth = tempValue.dqdss + ' / ' + tempValue.breakCntNoParking
        delete tempValue.dqdss
        delete tempValue.breakCntNoParking
        cardList.value = JSON.parse(JSON.stringify(dataRegroup(tempValue)))
        resolve(res.dataDetail)
        // flag === 'once' && (gridOptions.data = res.dataDetail)
      })
    })
  }

  // 整机状态表格行点击获取单锭详情数据
  const gridRefIngot = ref<BasicGridInstance>()
  const currRow = ref()
  const gridEvents: VxeGridListeners<overallUnitType> = {
    cellClick({ row }) {
      currRow.value = row
      gridRefIngot.value?.$grid?.commitProxy('query')
    }
  }
  const getSingleIngotData = () => {
    return new Promise<singleIngotType[]>((resolve) => {
      getLiShiZhuangTai(currRow.value.machineDocumentId).then((res: any) => {
        showDetail.value = true

        resolve(
          res.map((value) => {
            return {
              machineName: currRow.value.machineName,
              positionId: value.side + value.positionId,
              state: value.state,
              speed: value.speed,
              length: value.length,
              startTime: dayjs(value.startTime).format('YYYY-MM-DD HH:mm:ss')
            }
          })
        )
      })
    })
  }

  // 获取断头(弱捻)情况表格数据
  const getBrokenEndList = () => {
    return new Promise<brokenEndType[]>((resolve) => {
      getRuoNianList({
        overTime: 20, // 筛选数据
        machineDocumentIdList: machineryIdArr.value
      }).then((res: any) => {
        // this.ruoNianList = res
        // res.forEach((value: any) => {
        //   value.positionId = value.side + value.positionId
        //   value.breakDuration = Math.floor(value.breakDuration / 60)
        //   value.nonDuration = Math.floor(value.nonDuration / 60)
        //   value.twistDuration = Math.floor(value.twistDuration / 60)
        // })
        resolve(
          res.map((item) => {
            return {
              ...item,
              positionId: item.side + item.positionId,
              breakDuration: Math.floor(item.breakDuration / 60),
              nonDuration: Math.floor(item.nonDuration / 60),
              twistDuration: Math.floor(item.twistDuration / 60)
            }
          })
        )
      })
    })
  }

  onMounted(() => {
    getMaterialsAndMachineryData()
    clearTimeSet.value = setInterval(() => {
      if (canRefresh.value) {
        gridRef.value?.$grid?.commitProxy('query')
        gridRefBroken.value?.$grid?.commitProxy('query')
        // getCardAndOverallUnitData()
        // getBrokenEndList()
      }
    }, 10000)
  })
  onUnmounted(() => {
    clearInterval(clearTimeSet.value)
  })
</script>
<style scoped lang="scss">
  .top-card-container {
    display: flex;
    margin-bottom: 20px;
  }

  .el-scrollbar {
    height: auto;
  }

  .singleIngot-detail {
    margin-top: 30px;
  }

  .overall-unit {
    padding: 15px 20px 20px;
    background-color: #fff;
  }

  .brokenEnd-detail {
    padding: 20px;
    margin-top: 20px;
    background-color: #fff;
  }
</style>
